package tieba.core.utils;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import tieba.core.entity.Tie;
import tieba.core.entity.TieBar;
import tieba.core.entity.TiebaUser;
import tieba.core.exception.DefineException;
import tieba.core.exception.LoginErrorException;
import tieba.core.utils.baidu.a;
import cl.tools.http.method.BasicMethod;

import com.jayway.restassured.response.Cookie;
import com.jayway.restassured.response.Response;

public class TBUtils {

	public static Cookie getBAIDUID() {
		for (Entry<String, String> cookie : BasicMethod
				.get("http://www.baidu.com/").getCookies().entrySet()) {
			if (cookie.getKey().equals("BAIDUID")) {
				return new Cookie.Builder(cookie.getKey(), cookie.getValue())
						.build();
			}
		}
		return null;
	}

	public static String getToken(Cookie cookie) {
		String regex = ".login_token='([^']+)'";
		return CommonsUtils
				.regex(regex,
						BasicMethod
								.get("https://passport.baidu.com/v2/api/?getapi&class=login&tpl=mn&tangram=true",
										BasicMethod.given().cookie(cookie))
								.asString(), 1);
	}

	public static String checkAuthCode(TiebaUser user) {
		String body = BasicMethod.get(
				"https://passport.baidu.com/v2/api/?logincheck&token="
						+ user.getToken() + "&tpl=mn&apiver=v3&username="
						+ user.getUsername(),
				BasicMethod.given().cookies(user.getCookies())).asString();
		System.out.println("验证码返回页面"+body);
		String regex = "\"codeString\" : \"([^\"]*)?\"";
		String codestring = CommonsUtils.regex(regex, body, 1);
		if ("".equals(codestring))
			return null;
		else
			user.setCodestring(codestring);
		return codestring;
	}

	public static String authCodeToUrl(String codestring) {
		return "https://passport.baidu.com/cgi-bin/genimage?" + codestring;
	}

	public static TiebaUser login(TiebaUser user) {
		if (user.getVerifycode() == null
				|| "".equals(user.getVerifycode().trim())) {
			System.out.println("检测验证码");
			Cookie BAIDUID = TBUtils.getBAIDUID();
			System.out.println("获取BAIDUID");
			user.setCookies(CommonsUtils.CookieToMap(BAIDUID));
			user.setToken(TBUtils.getToken(BAIDUID));
			System.out.println("获取Token");
			user.setCodestring(TBUtils.checkAuthCode(user));
			System.out.println("获取验证码");
			if (user.getCodestring() != null) {
				user.setCodehref(authCodeToUrl(user.getCodestring()));
				System.out.println("抛出验证码异常");
				throw new LoginErrorException("验证码拦截", user);
			}
		}
		Map<String, Object> ps = new LinkedHashMap<>();
		String staticpage = "http://www.baidu.com/cache/user/html/jump.html";
		ps.put("charset", "utf-8");
		ps.put("token", user.getToken());
		ps.put("isPhone", "false");
		ps.put("index", "0");
		ps.put("staticpage", staticpage);
		ps.put("loginType", "1");
		ps.put("tpl", "mn");
		ps.put("callback", "parent.bdPass.api.login._postCallback");
		ps.put("username", user.getUsername());
		ps.put("password", user.getPassword());
		ps.put("verifycode", user.getVerifycode());
		ps.put("codestring", user.getCodestring());
		ps.put("mem_pass", "on");
		Response resp = BasicMethod.post(
				"https://passport.baidu.com/v2/api/?login", ps, BasicMethod
						.given().cookies(user.getCookies()));
		String body = resp.asString();
		String regex = "&error=([^'])'";
		String error = CommonsUtils.regex(regex, body, 1);
		System.out.println(body);
		System.out.println("错误代码:" + error);
		if (error == null || "".equals(error.trim()))
			throw new LoginErrorException("登陆有误!", user);
		if (Integer.parseInt(error) == 0) {
			user.setCookies(resp.cookies());
			user.setBDUSS(resp.cookie("BDUSS"));
		} else {
			throw new LoginErrorException("登陆失败!", user);
		}
		return user;
	}

	public static List<TieBar> getLikes(Cookie cookie) {
		String url = "http://tieba.baidu.com/mo/q/m?tn=bdFBW";
		String body = BasicMethod.get(url, BasicMethod.given().cookie(cookie))
				.asString();
		// System.out.println(body);
		List<String> fns = CommonsUtils
				.matches("data-fn=\"([^\"]+)\"", body, 1);
		List<String> fids = CommonsUtils
				.matches("data-fid=\"(\\w+)\"", body, 1);
		if (fids == null || fids.size() == 0)
			throw new DefineException("无法获取到关注的贴吧列表!", cookie.getValue());
		List<TieBar> bs = new ArrayList<>();
		TieBar bar = null;
		for (int index = 0; index < fids.size(); index++) {
			bar = new TieBar();
			bar.setFid(fids.get(index));
			bar.setFn(fns.get(index));
			bs.add(bar);
		}
		return bs;
	}

	public static String getTbs(Cookie cookie) {
		String url = "http://tieba.baidu.com/dc/common/tbs";
		String body = BasicMethod.get(url, BasicMethod.given().cookie(cookie))
				.asString();
		int isLogin = Integer.parseInt(CommonsUtils.regex("\"is_login\":(\\w)",
				body, 1));
		if (isLogin == 0)
			throw new DefineException("Cookie(BDUSS值)无效", cookie.getValue());
		else if (isLogin == 1)
			return CommonsUtils.regex("\"tbs\":\"([^\"]+)\"", body, 1);
		return null;
	}

	public static String getSign(Map<String, Object> ps) {
		String data = "";
		for (Entry<String, Object> param : ps.entrySet()) {
			data += param.getKey() + "=" + param.getValue();
		}
		return new a().b(data).toUpperCase();
	}

	public static List<TieBar> getClientLikes(String bduss) {
		String url = "http://c.tieba.baidu.com/c/f/forum/forumrecommend";
		Map<String, Object> ps = new LinkedHashMap<>();
		ps.put("BDUSS", bduss);
		ps.put("sign", TBUtils.getSign(ps));
		String body = BasicMethod.post(url, ps).asString();
		// System.out.println(body);
		Integer error_code = CommonsUtils.getErrorCode(body);
		if (error_code == null || error_code != 0)
			throw new DefineException("获取关注的贴吧列表失败!");
		body = CommonsUtils.regex("\"like_forum\":\\[([^\\]]+)\\]", body, 1);
		// System.out.println(body);
		if (body == null || "".equals(body.trim()))
			throw new DefineException("请确认Cookie正确性!");
		List<String> fids = CommonsUtils
				.matches("\"forum_id\":(\\w+)", body, 1);
		List<String> fns = CommonsUtils.matches("\"forum_name\":\"([^\"]+)\"",
				body, 1);
		List<String> isSign = CommonsUtils
				.matches("\"is_sign\":(\\w)", body, 1);
		List<TieBar> bs = new ArrayList<>();
		TieBar bar = null;
		for (int index = 0; index < fids.size(); index++) {
			bar = new TieBar();
			bar.setFid(fids.get(index));
			int i = -1;
			String fn = (i = fns.get(index).indexOf("\\u", 0)) == -1 ? fns
					.get(index) : CommonsUtils.unicodeConvert(fns.get(index));
			bar.setFn(fn);
			bar.setSign(Integer.parseInt(isSign.get(index)));
			bs.add(bar);
		}
		return bs;
	}

	public static TieBar getBarByTid(String tid) {
		String url = "http://c.tieba.baidu.com/c/f/pb/page";
		Map<String, Object> ps = new LinkedHashMap<>();
		ps.put("kz", tid);
		ps.put("sign", getSign(ps));
		String body = BasicMethod.post(url, ps).asString();
		// System.out.println(body);
		body = CommonsUtils.regex("\"forum\":\\{([^\\}]+)\\}", body, 1);
		// System.out.println(body);
		TieBar bar = new TieBar();
		bar.setFn((CommonsUtils.unicodeConvert(CommonsUtils.regex(
				"\"name\":\"([^\"]+)\"", body, 1))));
		bar.setFid(CommonsUtils.regex("\"id\":(\\w+)", body, 1));
		return bar;
	}

	public static List<Tie> 获取帖子列表() {
		return null;

	}

	public static List<TiebaUser> 获取用户列表() {
		return null;

	}
}
